import hashlib
import json
from tkinter.font import names

import jwt
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

# Create your views here.

from .models import Order,Goods,User,Sort
def empty(c):
    return c is None or str(c).strip()==''

def jiaomi(pwd):
    return hashlib.md5(pwd.enmp()).hexdigest()

@csrf_exempt
def login(request):
    if request.method=="POST":
        data=json.loads(request.body)
        username=data.get('username')
        password=data.get('password')

        if empty(username)or empty(password):
            return JsonResponse({
                'msg':"不能为空"
            },status=400)

        if User.objects.filter(username=username).exists()==False:
            return JsonResponse({
                'msg':"用户不存在"
            },status=400)

        user=User.objects.get(username=username)
        if user.password!=password:
            return JsonResponse({
                'msg':"密码错误"
            },status=400)

        pay={'name':user.username,'pwd':user.password}
        mi='123456'
        token=jwt.encode(pay,mi)
        return JsonResponse({
            'msg':'登录成功',
            'token':token
        },status=200)

@csrf_exempt
def getSort(request):
    data=Sort.objects.all()

    ls=[]
    for i in data:
        ls.append(model_to_dict(i))
    return JsonResponse({
        'msg':"查询成功",
        'data':ls
    },status=200)

@csrf_exempt
def getGoods(request):
    if request.method=="GET":
        data=Goods.objects.all()
        total=len(data)
        page=request.GET.get('page',1)
        size=request.GET.get('size','')or 10
        #商品分类（拉列表-加载商品分类数据）筛选
        id=request.GET.get('id')
        if id:
            data=data.filter(gid_id=id)
        data=Paginator(data,size).get_page(page)

        ls=[]
        for i in data:
            ls.append(model_to_dict(i))
        return JsonResponse({
            'msg':"查询成功",
            'data':ls,
            'total':total
        },status=200)
    elif request.method=="POST":
        data=json.loads(request.body)
        gname = data.get('gname')

        gnum = data.get('gnum')

        a=Goods.objects.create(
            gname=gname,
            gid_id=data['gid_id'],
            gprice=data['gprice'],
            gnum=gnum

        )

        return JsonResponse({
            'msg':"添加成功",
            'data':model_to_dict(a)
        },status=200)

@csrf_exempt
def upGoods(request,id):
    goods=Goods.objects.get(id=id)
    if request.method=='PUT':
        data=json.loads(request.body)
        goods.gname=data.get('gname')
        goods.gid_id = data.get('gid_id')
        goods.gprice = data.get('gprice')
        goods.gnum = data.get('gnum')
        goods.save()

        return JsonResponse({
            'msg':"修改成功",
            'data':model_to_dict(goods)
        },status=200)

    elif request.method=="DELETE":
        if Order.objects.filter(oid_id=id).exists()==True:
            return JsonResponse({
                'error':"订单存在 不能删除"
            })

        goods.delete()
        return JsonResponse({'message':'删除成功'})

@csrf_exempt
def addOrder(request):
    if request.method=="POST":
        data=json.loads(request.body)

        jieguo=Order.objects.create(
            oid_id=data['oid_id'],
            onum=data['onum'],
            oprice=data['oprice'],
            oname=data['oname'],
            uid_id=data['uid_id'],
        )
        #对应商品库存减少相应的数量

        #根据商品ID，找到数据库里对应的商品
        shop=Goods.objects.get(id=data['oid_id'])
        #原来的库存-买了的数量=新库存
        shop.gnum=int(shop.gnum)-int(data['onum'])
        shop.save()
        return JsonResponse({'message':'创建成功','data':model_to_dict(jieguo)})
    elif request.method=="GET":
        all_data=Order.objects.all()
        ls=[]
        #按商品名称/日期范围筛选，分页展示
        #在商品表里查通过名字查id
        oname=request.GET.get('oname')
        o_id=Goods.objects.get(gname=oname).id
        if o_id:
            all_data=all_data.filter(oid_id=o_id)

        for i in all_data:
            ls.append(model_to_dict(i))

        return JsonResponse({'data':ls})


